package com.hongxun.budget.ui.fragment.sg;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.amap.api.maps.offlinemap.OfflineMapCity;
import com.hongxun.budget.R;
import com.hongxun.budget.greendao.DPictureEntityDao;
import com.hongxun.budget.ui.dialog.NoticeDialog;
import com.hongxun.budget.ui.fragment.BaseListFragment;
import com.hongxun.budget.utils.GreenDaoManager;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.SgDBUtils;
import com.hongxun.budget.utils.SgXUtils;
import com.hongxun.budget.utils.T;
import com.hongxun.greenentity.sg.CPBaseEntity;
import com.hongxun.greenentity.tk.BDataDictionaryEntity;
import com.hongxun.interfaces.ClickListener;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 清除缓存
 */
public class ClearCacheFragment extends BaseListFragment implements Handler.Callback {
    private SuperAdapter adapter;
    private List<BDataDictionaryEntity> data = new ArrayList<>();
    private List<OfflineMapCity> mapCityList;
    private List<CPBaseEntity> entityList;
    private Handler handler = new Handler(this);

    @Override
    public boolean handleMessage(final Message msg) {
        switch (msg.what) {
            case 1:
                BDataDictionaryEntity entity = (BDataDictionaryEntity) msg.obj;
                List<OfflineMapCity> cities = new ArrayList<>();
                cities.addAll(mapCityList);
                for (OfflineMapCity mapCity : cities) {
                    if (mapCity.getCity().equals(entity.getDValue())) {
                        mapCityList.remove(mapCity);
                        break;
                    }
                }
                SPUtils.put(context, "CITYKEY", JSON.toJSONString(mapCityList));
                break;
            case 2:
                Observable.just(msg.obj).subscribeOn(Schedulers.io()).map(new Func1<Object, String>() {
                    @Override
                    public String call(Object bean) {
                        BDataDictionaryEntity entity = (BDataDictionaryEntity) bean;
                        try {
                            SgXUtils.delProjectMiddleCheck(entity.getGuid());
                            SgXUtils.delProjectPresent(entity.getGuid());
                            SgXUtils.delProjectProgress(entity.getGuid());
                            GreenDaoManager.getInstance().getmDaoSession()
                                    .getDPictureEntityDao()
                                    .queryBuilder()
                                    .where(DPictureEntityDao.Properties.PGuid.eq(entity.getGuid()))
                                    .buildDelete()
                                    .executeDeleteWithoutDetachingEntities();
                            GreenDaoManager.getInstance().getmDaoSession()
                                    .getCPBaseEntityDao()
                                    .deleteByKey(entity.getGuid());
                        } catch (Exception e) {
                            return "请直接到手机设置里清除APP数据";
                        }
                        return "已清除";
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<String>() {
                    @Override
                    public void call(String str) {
                        T.showShort(context, str);
                    }
                });
                break;
        }
        return false;
    }

    @Override
    public void onResume() {
        super.onResume();
        initDault();
    }

    @Override
    public void initDault() {
        data.clear();
        Observable.just("").subscribeOn(Schedulers.io()).map(new Func1<String, Boolean>() {
            @Override
            public Boolean call(String s) {
                //本地已缓存的地图列表
                String s1 = String.valueOf(SPUtils.get(context, "CITYKEY", ""));
                mapCityList = JSON.parseArray(s1, OfflineMapCity.class);
                if (mapCityList != null) {
                    for (OfflineMapCity city : mapCityList) {
                        BDataDictionaryEntity entity = new BDataDictionaryEntity();
                        entity.setDCode("1");
                        entity.setDRemarks("6.0以下缓存地图");
                        entity.setDValue(city.getCity());
                        data.add(entity);
                    }
                }
                //服务器已删除/归档的项目
                entityList = SgDBUtils.getCPBaseList(true);
                if (entityList != null) {
                    for (CPBaseEntity baseEntity : entityList) {
                        BDataDictionaryEntity entity = new BDataDictionaryEntity();
                        entity.setGuid(baseEntity.getGuid());
                        entity.setDCode("2");
                        entity.setDRemarks("已删除或已归档的施工项目");
                        entity.setDValue(baseEntity.getPBName());
                        data.add(entity);
                    }
                }
                return true;
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean aBoolean) {
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public SuperAdapter getAdapter() {
        adapter = new SuperAdapter<BDataDictionaryEntity>(R.layout.sg_adapter_clearcache) {
            @Override
            public void bindView(ViewHolder viewHolder, final BDataDictionaryEntity o, int i) {
                TextView view1 = viewHolder.getView(R.id.device_type);
                TextView view2 = viewHolder.getView(R.id.name);
                view1.setText(o.getDRemarks());
                view2.setText(o.getDValue());
                viewHolder.getView(R.id.delete_old_device).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        delDialog(o);
                    }
                });
            }
        };
        adapter.setData(data);
        adapter.setEmptyDataView(R.layout.view_empty);
        return adapter;
    }

    private void delDialog(final BDataDictionaryEntity o) {
        new NoticeDialog().setTitle("删除提示")
                .setMsg(o.getDValue())
                .setCancelButton(null, null)
                .setConfirmButton("确定", new ClickListener() {
                    @Override
                    public void click() {
                        data.remove(o);
                        adapter.notifyDataSetChanged();
                        Message msg = handler.obtainMessage();
                        msg.what = Integer.valueOf(o.getDCode());
                        msg.obj = o;
                        handler.sendMessage(msg);
                    }
                }).show(getFragmentManager(), "");
    }
}
